import NavBar from '@/components/NavBar';
import { useAppSelector } from '@/store';
import {
  clearTokenAction,
  profileAction,
  uploadPhotoAction,
} from '@/store/action/user';
import { List, Popup, Toast, Input, DatePicker, Dialog } from 'antd-mobile';
import { useEffect, useRef, useState } from 'react';
import { useDispatch } from 'react-redux';
import styles from './index.module.scss';
import { editProfileAction } from '@/store/action/user';
import Textarea from '@/components/Textarea';
import dayjs from 'dayjs';
import { removeToken } from '@/utils/storage';
import history from '@/utils/history';

export default function ProfileEdit() {
  const dispatch = useDispatch();
  useEffect(() => {
    dispatch(profileAction());
  }, [dispatch]);
  const { profile } = useAppSelector((state) => state.user);
  const [visible, setVisible] = useState(false); //设置头像 性别底部弹出显示隐藏
  const [visibleRight, setVisibleRight] = useState(false); //设置昵称右侧弹出显示隐藏
  const [nameOrIntro, setNameOrIntro] = useState(''); //通过点击判定进行切换值
  const tempRef = useRef(''); //用于判断点击那个内容
  //使用原生input 实现上传
  const uploadRef = useRef<HTMLInputElement>(null);
  const [showDatePicker, setShowDatePicker] = useState(false);

  //点击头像或者性别
  const handleClick = (val: string) => {
    tempRef.current = val;
    setVisible(true);
  };
  //编辑性别
  const editGender = async (gender: number) => {
    await dispatch(editProfileAction({ gender }));
    setVisible(false);
    Toast.show({
      content: '修改成功！',
      duration: 1000,
    });
    //刷新页面
    await dispatch(profileAction());
  };
  //编辑昵称/简介
  const handleUsername = async (data: { name?: string; intro?: string }) => {
    await dispatch(editProfileAction(data));
    setVisibleRight(false);
    Toast.show({ content: '修改成功！', duration: 1000 });
    //刷新页面
    dispatch(profileAction());
  };
  //监听键盘事件
  const handlekeyDown = (
    e: React.KeyboardEvent<HTMLInputElement | HTMLTextAreaElement>
  ) => {
    if (e.key === 'Enter') {
      handleUsername({ [tempRef.current]: nameOrIntro });
    }
  };
  //原生input上传头像
  const uploadChange = async (e: React.ChangeEvent<HTMLInputElement>) => {
    console.log(e.target.files);
    if (e.target.files) {
      setVisible(false);
      const formData = new FormData();
      formData.append('photo', e.target.files[0]);
      await dispatch(uploadPhotoAction(formData));
      Toast.show({ content: '修改成功！', duration: 1000 });
      // dispatch(profileAction());
    }
  };
  //判断点击昵称还是简介
  const handleClickNAI = (val: string) => {
    tempRef.current = val;
    if (val === 'intro') setNameOrIntro(profile.intro ? profile.intro : '');
    if (val === 'name') setNameOrIntro(profile.name);
    setVisibleRight(true);
  };
  //文本域事件
  const handleTextarea = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
    console.log(e.target.value);
    setNameOrIntro(e.target.value);
  };
  //关闭右侧弹窗
  const handleCloseRight = () => {
    //关闭时还原原始内容
    if (tempRef.current === 'name') {
      setNameOrIntro(profile.name);
    }
    if (tempRef.current === 'intro') {
      setNameOrIntro(profile.intro ? profile.intro : '');
    }
    setVisibleRight(false);
  };
  //日期
  const handleComfire = async (val: Date) => {
    console.log(dayjs(val).format('YYYY-MM-DD'));
    const birthday = dayjs(val).format('YYYY-MM-DD');
    await dispatch(editProfileAction({ birthday }));
    setShowDatePicker(false);
    Toast.show({ content: '修改成功！', duration: 1000 });
    dispatch(profileAction());
  };
  //登出
  const handdleLogout = () => {
    Dialog.confirm({
      title: '温馨提示',
      content: '您确定退出吗？',
      onConfirm: () => {
        //清理token
        removeToken();
        //清理redux的token
        dispatch(clearTokenAction());
        //跳转登录
        history.push('/login');
        Toast.show({ content: '退出登录成功', duration: 1000 });
      },
    });
  };
  return (
    <div className={styles.root}>
      <div className="content">
        {/* 顶部导航栏 */}
        <NavBar>个人资料</NavBar>

        <div className="wrapper">
          {/* 列表一：显示头像、昵称、简介 */}
          <List className="profile-list">
            <List.Item
              arrow
              extra={<img className="avatar" src={profile.photo} alt="" />}
              onClick={() => handleClick('photo')}
            >
              头像
            </List.Item>

            <List.Item
              arrow
              extra={profile.name}
              // onClick={() => setVisibleRight(true)}
              onClick={() => handleClickNAI('name')}
            >
              昵称
            </List.Item>

            <List.Item
              arrow
              extra={
                <span className="intro">
                  {profile.intro ? profile.intro : '未填写'}
                </span>
              }
              onClick={() => handleClickNAI('intro')}
            >
              简介
            </List.Item>

            <List.Item
              arrow
              extra={profile.gender === 1 ? '男' : '女'}
              onClick={() => handleClick('gender')}
            >
              性别
            </List.Item>
            <List.Item
              arrow
              extra={profile.birthday}
              onClick={() => setShowDatePicker(true)}
            >
              生日
            </List.Item>
          </List>

          {/* 文件选择框，用于头像图片的上传 */}
          {/* <input className="avatar-upload" type="file" /> */}
          <input
            onChange={(e) => uploadChange(e)}
            className="avatar-upload"
            type="file"
            ref={uploadRef}
            accept=".jpg,.jpeg,.png"
            // style={{ display: 'none' }}
          />
        </div>

        {/* 底部栏：退出登录按钮 */}
        <div className="logout">
          <button className="btn" onClick={() => handdleLogout()}>
            退出登录
          </button>
        </div>
      </div>

      {/* 底部弹出层 */}
      <Popup
        visible={visible}
        position="bottom"
        bodyClassName="popup-bottom-list"
        onMaskClick={() => setVisible(false)}
      >
        {tempRef.current === 'photo' ? (
          <>
            <div
              className="list-item"
              onClick={() => uploadRef.current?.click()} //拍照也做成上传，不做拍照
            >
              拍照
            </div>
            <div
              className="list-item"
              onClick={() => uploadRef.current?.click()} //点击时触发上传input的点击，后面时触发，所以是click
            >
              本地选择
            </div>
            <div className="list-item" onClick={() => setVisible(false)}>
              取消
            </div>
          </>
        ) : (
          <>
            <div className="list-item" onClick={() => editGender(1)}>
              男
            </div>
            <div className="list-item" onClick={() => editGender(0)}>
              女
            </div>
            <div className="list-item" onClick={() => setVisible(false)}>
              取消
            </div>
          </>
        )}
      </Popup>
      {/* 右侧弹出层 */}
      <Popup
        destroyOnClose={true}
        visible={visibleRight}
        bodyClassName="popup-right"
        onMaskClick={() => handleCloseRight()}
        position="right"
        bodyStyle={{ minWidth: '100vw' }}
      >
        <NavBar
          // onBack={() => setVisibleRight(false)}
          onBack={() => handleCloseRight()}
          right={
            <span
              style={{ color: '#fc6627' }}
              onClick={() => handleUsername({ [tempRef.current]: nameOrIntro })}
            >
              提交
            </span>
          }
        >
          {tempRef.current === 'name' ? '编辑昵称' : '编辑简介'}
        </NavBar>
        {tempRef.current === 'name' ? (
          <>
            <div className="inpRight">
              <Input
                placeholder="请输入内容"
                value={nameOrIntro}
                onKeyDown={(e) => handlekeyDown(e)}
                onChange={(val) => {
                  setNameOrIntro(val);
                }}
              />
            </div>
          </>
        ) : (
          <Textarea
            maxLength={100}
            value={nameOrIntro}
            placeholder="请输入简介"
            onChange={(e) => handleTextarea(e)}
            onKeyDown={(e) => handlekeyDown(e)}
          ></Textarea>
        )}
      </Popup>
      {/* 日期弹窗 */}
      <DatePicker
        visible={showDatePicker}
        min={new Date('1949-10-01')}
        max={new Date()}
        title="选择生日"
        value={new Date(profile.birthday)}
        onClose={() => {
          setShowDatePicker(false);
        }}
        precision="day"
        onConfirm={(val) => handleComfire(val)}
      />
    </div>
  );
}
